import { FC, memo, ReactElement, useCallback, useEffect, useMemo, useRef, useState } from 'react'

import React from 'react'
import { INewsList, NewItem } from 'Src/typings/interface'

import style from './index.scss'
import NewsItem from './NewsItem'

import { DotLoading, InfiniteScroll, PullToRefresh, Toast } from 'antd-mobile'
import { sleep } from 'antd-mobile/es/utils/sleep'
import { PullStatus } from 'antd-mobile/es/components/pull-to-refresh'

import 'antd-mobile/es/global'

interface IProps {
  list: INewsList
}

const statusRecord: Record<PullStatus, string> = {
  pulling: '用力拉',
  canRelease: '松开吧',
  refreshing: '玩命加载中...',
  complete: '好啦',
}

const NewsList: FC<IProps> = ({ list }): ReactElement => {
  console.log('news-list render')

  const [data, setData] = useState<NewItem[]>(list.pageList[0])

  const currentNewsType = useRef<string>(list.newsType)

  useEffect(() => {
    // 监听 newsType 的变化 更新data
    if (currentNewsType.current !== list.newsType) {
      window.scrollTo(0, 0)
      setData(list.pageList[0])
      currentNewsType.current = list.newsType
      pageIndexRef.current = 0
    }
  }, [list])

  // 缓存 pageIndex
  const pageIndexRef = useRef<number>(0)

  // 判断是否还有下一页 top 加载 需要判断 等号条件成立 而 bottom 加载不需要 等号条件成立
  const hasMore = useCallback((target: INewsList, pageIndex: number) => {
    return pageIndex <= target.pageList.length - 1
  }, [])

  // 获取下一页
  const getNextData = useCallback((target: INewsList, pageIndex: number) => {
    return hasMore(target, pageIndex) ? target.pageList[pageIndex] : []
  }, [])

  // 加载更多
  const loadMore = useCallback(
    async (type: string) => {
      await sleep(1500)
      if (!hasMore(list, pageIndexRef.current)) {
        Toast.show({
          content: '没有更多数据啦~',
        })
        return
      }
      const nextData = getNextData(list, ++pageIndexRef.current)
      console.log(nextData)
      nextData.length
        ? type === 'top'
          ? setData([...nextData, ...data])
          : setData([...data, ...nextData])
        : Toast.show({
            content: '没有更多数据啦~',
          })
    },
    [list, data],
  )
  console.log(data)
  return (
    <div className={`${style['news-list']}`}>
      {/* 下拉加载 */}
      <PullToRefresh
        onRefresh={() => loadMore('top')}
        renderText={(status) => {
          return <div>{statusRecord[status]}</div>
        }}
      >
        {data && data.map((item: NewItem) => <NewsItem key={item.uniquekey} item={item} />)}
      </PullToRefresh>
      {/* 无限滚动 hasMore 属性表示是否还有下一页 这里 必须给当前 pageIndex + 1 因为要去掉 = 号成立的条件*/}
      <InfiniteScroll loadMore={() => loadMore('bottom')} hasMore={hasMore(list, pageIndexRef.current + 1)} />
    </div>
  )
}

export default memo(NewsList)
